-- IntelligencePCM
-- created by cheny3 Oct/13/2016
-- 智能电脑

module("IntelligencePCM", package.seeall);

local pcBonus = {};
local pcNews = {};
local typeNews = {};
local whenLeaveDungeon;

-- 载入配置表
local _init = false;
local loadCsv = function()
    if _init then return end
    _init = true;

    -- 转换下信息表
    local intelligence_pc_bonus_CSV = get_intelligence_pc_bonus_CSV();
    for i = 1, #intelligence_pc_bonus_CSV do
        local row = intelligence_pc_bonus_CSV[i];
        pcBonus[row.id] = row;
    end

    local intelligence_pc_news_CSV = get_intelligence_pc_news_CSV();
    for i = 1, #intelligence_pc_news_CSV do
        local row = intelligence_pc_news_CSV[i];
        pcNews[row.id] = row;

        -- 按类型统计
        local type = row.type;
        if not typeNews[type] then
            typeNews[type]= {};
        end

        table.insert(typeNews[type], row.id);
    end

    intelligence_pc_bonus_CSV = {};
    intelligence_pc_news_CSV = {};
end

-- 模块初始化
function init()
    loadCsv();

    EventMgr.removeAll("IntelligencePCM");

    -- 关注离开地牢事件
    EventMgr.register("IntelligencePCM", event.LEAVE_DUNGEON, whenLeaveDungeon);
end

-- 离开地牢
whenLeaveDungeon = function()
    -- 删除统计
    for _, id in pairs(table.keys(pcNews)) do
        BuffDataM.set("pc_news_read", id, 0);
    end
end

-- 检索新闻
function queryNews(id, path)
    local m = pcNews[id];

    if not m or not path then
        return m;
    end

    return m[path];
end

-- 检索奖励
function queryBonus(id, path)
    local m = pcBonus[id];

    if not m or not path then
        return m;
    end

    return m[path];
end

-- 抽取格子数据
function fetchPcData()
    local bonusId = fetchPcBonus();
    local newsIds = fetchPcNews();

    return {["news_ids"] = newsIds, ["bonus_id"] = bonusId};
end

-- 获取玩家某类型尚未阅读的新闻
function getUnreadNews(type)
    local ret = {};
    local ids = typeNews[type];

    for _, id in pairs(ids) do
        if BuffDataM.query("pc_news_read", id) ~= 1 then
            table.insert(ret, id);
        end
    end

    return ret;
end

-- 抽取奖励信息
function fetchPcBonus()
    local seed = DungeonM.getRandSeed("pc_bonus");
    local fetchArr = {};

    local ids = table.keys(pcBonus);
    table.sort(ids);
    for _, id in pairs(ids) do
        local info = queryBonus(id);
        table.insert(fetchArr, {["ratio"] = info.ratio, ["id"] = id});
    end

    -- 抽取
    return fetchElemBySeed(fetchArr, seed)["id"];
end

-- 抽取新闻
function fetchPcNews()
    local ret = {};

    -- 每种类型抽一个
    for _, type in pairs(table.keys(typeNews)) do
        -- 从没读过的里面抽取
        local ids = getUnreadNews(type);

        if #ids <= 0 then
            -- 都读过了，随机抽
            ids = typeNews[type];
        end

        -- 排序
        table.sort(ids);

        local seed = DungeonM.getRandSeed("pc_news");
        local id = ids[seed % #ids + 1];

        ret[type] = id;
    end

    return ret;
end

-- 玩家是否已经阅读了新闻
function hasUserRead(id)
    return BuffDataM.query("pc_news_read", id) == 1;
end

-- 玩家阅读了新闻
function userReadNews(pos, id)
    local grid = DungeonM.getGridByPos(pos);

    -- 如果不是电脑
    if grid.type ~= GRID_TYPE_INTELLIGENCE_PC or
        grid.state == GRID_STATE_DISABLE then
        trace("IntelligencePCM", "格子(%d)不是只能电脑或已失效。", pos);
        return false;
    end

    if not queryNews(id) then
        trace("IntelligencePCM", "没有id为:%d的新闻。", id);
        return false;
    end

    if not hasUserRead(id) then
        -- 设置已经阅读过
        BuffDataM.set("pc_news_read", id, 1);
    end

    return true;
end

-- 玩家领取奖励
function takePcBonus(pos)
    local grid = DungeonM.getGridByPos(pos);

    -- 如果不是电脑
    if grid.type ~= GRID_TYPE_INTELLIGENCE_PC or
        grid.state == GRID_STATE_DISABLE then
        trace("IntelligencePCM", "格子(%d)不是智能电脑或已失效。", pos);
        return false;
    end

    local bonusId = grid.bonus_id or 0;
    local bonusList = table.deepcopy(queryBonus(bonusId, "bonus"));
    if #bonusList <= 0 then
        trace("IntelligencePCM", "格子(%d)当前没有奖励，无法领取。", pos);
        return false;
    end

    -- 加成
    local specialProp = PropM.combine(ME.user, "intelligence_pc", 1);
    for index, bonus in pairs(bonusList) do
        if specialProp[3] > 0 then
            bonus[3] = PropM.apply(specialProp, bonus[3]);
        end

        bonusList[index] = bonus;
        BonusM.doBonus(bonus, "pc_bonus");
    end

    -- 领取完就删掉
    grid.bonus_id = nil;

    -- 抛出事件
    EventMgr.fire(event.TAKE_PC_BONUS, {["pos"] = pos, ["bonus"] = bonusList, ["bonusId"] = bonusId});

    return true;
end

-- 破旧的电脑奖励
function takeBrokenPcBonus(pos)
    local grid = DungeonM.getGridByPos(pos);

    -- 如果不是电脑
    if grid.type ~= GRID_TYPE_BROKEN_PC or
        grid.state == GRID_STATE_DISABLE then
        trace("IntelligencePCM", "格子(%d)不是破旧电脑或已失效。", pos);
        return false;
    end

    -- 最多扣到剩下1血
    local damage = math.min(ME.user:getHp() - 1, 10);
    CombatM.receiveDamage(ME.user, ME.user, damage, 0);

    local bonusList = grid.bonus or {};
    for _, bonus in pairs(bonusList) do
        BonusM.doBonus(bonus, "broken_pc_bonus");
    end

    grid:changeState(GRID_STATE_DISABLE);

    EventMgr.fire(event.TAKE_BROKEN_PC_BONUS, {["pos"] = pos, ["bonus"] = bonusList, });

    return true;
end